package com.changgou.order.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.pojo.OrderLog;
import com.changgou.order.service.OrderService;
import entity.RedisConfig;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = {"${mq.pay.queue.order}"})
public class OrderMessageListener {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /****
     * 监听消息
     * @param msg
     */
    @RabbitHandler
    public void consumeMessage(@Payload String msg) {
        RedisConfig.convertRedisTemplate(redisTemplate);

        //转化消息
        Map<String, String> msgMap = JSON.parseObject(msg, Map.class);
        //return_code=SUCCESS
        String return_code = msgMap.get("return_code");
        //业务结果
        String result_code = msgMap.get("result_code");

        //返回成功
        if (return_code.equalsIgnoreCase("SUCCESS")) {
            //获取商户订单号out_trade_no
            String out_trade_no = msgMap.get("out_trade_no");
            //查询日志
            OrderLog orderLog = (OrderLog) redisTemplate.boundHashOps("OrderLog").get(out_trade_no);

            //如果支付成功
            if (result_code.equalsIgnoreCase("SUCCESS")) {
                //修改订单状态
                orderService.updateStatus(orderLog.getUsername(), orderLog.getOrderId(), msgMap.get("transaction_id"), orderLog);
            } else {
                //取消订单，回滚库存
                orderService.deleteOrder(orderLog);
            }
        }
    }
}
